package com.course.android.activity.base;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baselib.android.utils.Logger;
import com.baselib.android.utils.ToastTool;
import com.course.model.HttpConfigBean;
import com.course.utils.web.HttpRespCallBack;

import org.apache.commons.lang.StringUtils;

import java.util.List;

public abstract class BaseNetActivity extends BaseActivity implements HttpRespCallBack {


    @Override
    public void onReqStart(HttpConfigBean flag) {

    }

    @Override
    public void onReqFinish(HttpConfigBean flag) {

    }

    @Override
    public void onReqFail(HttpConfigBean flag, Exception e, String errorMsg) {
        if (flag.isErrorToast() && StringUtils.isNotBlank(errorMsg)) {
            ToastTool.show(this, errorMsg);
        }
    }

    @Override
    public void onSuccess(HttpConfigBean flag, boolean page, Object o) {
        if (page) {
            if (o instanceof  JSONArray){
                onData(flag,o==null?null: JSONArray.parseArray(o.toString(), flag.getClas()));
                return;
            }
            JSONObject json = (JSONObject) o;
            int total = json.getIntValue("total");
            int pageNum = json.getIntValue("pageNum");
            int pageSize = json.getIntValue("pageSize");
            onPageData(flag, pageNum, pageSize, total,
                    JSONArray.parseArray(json.getJSONArray("data").toJSONString()
                            , flag.getClas()));
            return;
        }
        if (flag.getClas().equals(String.class)) {
            onData(flag, o.toString());
            return;
        }
        onData(flag,o==null?null: JSONObject.parseObject(o.toString(), flag.getClas()));
    }

    public abstract <T> void onData(HttpConfigBean flag, T o);

    public abstract <T> void onPageData(HttpConfigBean flag, int pageNum, int pageSize, int total, List<T> array);
}
